﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace last.fm
{
	public static class Auth
	{
		public static String getToken()
		{
			KeyValuePair<String, String> methodvalue = new KeyValuePair<string, string>("method", "auth.gettoken");
			KeyValuePair<String, String> keyvalue = new KeyValuePair<string, string>("api_key", LastFmWebservice.apiKey);
			XElement resultXML = LastFmWebservice.Request(methodvalue, keyvalue);
			if (resultXML.Attribute("status").Value == "ok")
			{
				return resultXML.Element("token").Value;
			}
			else
			{
				return null;
			}
		}

		public static Session getSession(String token)
		{
			KeyValuePair<String, String> methodvalue = new KeyValuePair<string, string>("method", "auth.getsession");
			KeyValuePair<String, String> keyvalue = new KeyValuePair<string, string>("token", token);
			KeyValuePair<String, String> tokenvalue = new KeyValuePair<string, string>("api_key", LastFmWebservice.apiKey);
			XElement resultXML = LastFmWebservice.Request(methodvalue, keyvalue, tokenvalue);
			if (resultXML.Attribute("status").Value == "ok")
			{
				String name = resultXML.Element("session").Element("name").Value;
				String custkey = resultXML.Element("session").Element("key").Value;
				Boolean subscriber = resultXML.Element("session").Element("subscriber").Value == "1" ? true : false;
				Session session = new Session(name, custkey, subscriber);
				return session;
			}
			else
			{
				return null;
			}
		}

		public static Session getMobileSession(String username, String password)
		{
			KeyValuePair<String, String> methodvalue = new KeyValuePair<string, string>("method", "auth.getmobilesession");
			KeyValuePair<String, String> usernamevalue = new KeyValuePair<string, string>("username", username);
			KeyValuePair<String, String> authvalue = new KeyValuePair<string, string>("authToken", LastFmWebservice.MD5Encrypt(username + LastFmWebservice.MD5Encrypt(password)));
			KeyValuePair<String, String> keyvalue = new KeyValuePair<string, string>("api_key", LastFmWebservice.apiKey);
			XElement resultXML = LastFmWebservice.Request(methodvalue, usernamevalue, authvalue, keyvalue);
			if (resultXML.Attribute("status").Value == "ok")
			{
				String name = resultXML.Element("session").Element("name").Value;
				String custkey = resultXML.Element("session").Element("key").Value;
				Boolean subscriber = resultXML.Element("session").Element("subscriber").Value == "1" ? true : false;
				Session session = new Session(name, custkey, subscriber);
				return session;
			}
			else
			{
				return null;
			}
		}
	}
}
